function findCircleNum(isConnected) {
  const n = isConnected.length
  const dsu = new DSU(n)
  for (let i = 0; i < n; i++) {
    for (let j = i + 1; j < n; j++) {
      if (isConnected[i][j] === 1) {
        dsu.union(i, j)
      }
    }
  }
  return dsu.count
}

class DSU {
  constructor(n) {
    this.count = n
    this.parent = new Array(n)
    for (let i = 0; i < n; i++) {
      this.parent[i] = i
    }
  }

  find(p) {
    let root = p
    while (this.parent[root] !== root) {
      root = this.parent[root]
    }
    while (this.parent[p] !== p) {
      let x = p
      p = this.parent[p]
      this.parent[x] = root
    }
    return root
  }

  union(p, q) {
    let rootP = this.find(p)
    let rootQ = this.find(q)
    if (rootP === rootQ) {
      return
    }
    this.parent[rootP] = rootQ
    this.count--
  }
}